<template>
  <div class="copy-code-container">
    <div class="code-palce-container" :class="{ 'show-code': showCode }">
      <el-button  v-if="showCode" class="copeBtn" type="info" icon="el-icon-document" size="mini" @click="handleCopy">复制</el-button>
      <el-button  v-else class="copeBtn" type="info" icon="el-icon-document-checked" size="mini" @click="handleCopy">复制成功</el-button>
      <div class="code-box" v-highlight>
        <pre>
            <code style="margin: 0;" class="javascirpt">{{code}}</code>
        </pre>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "codeBlock",
  data() {
    return {
      showCode: true,
    };
  },
  props: {
    code: {
      type: String,
      default: "",
    },
  },
  methods: {
    handeShowCode() {
      this.showCode = !this.showCode;
    },
    handleCopy() {
      const value = this.code;
    /*   const clipboardObj = navigator.clipboard;
      clipboardObj.writeText(value); */
      this.copyValue(value)
      this.showCode=false
    },
        // 先给要复制的文本或者按钮加上点击事件后，并将要复制的值传过来
    async copyValue(val) {
      if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard 向剪贴板写文本
        // this.$message.success('复制成功')
        return navigator.clipboard.writeText(val)
        this.showCode=false
      } else {
        // 创建text area
        const textArea = document.createElement('textarea')
        textArea.value = val
        // 使text area不在viewport，同时设置不可见
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        // this.$message.success('复制成功')
        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand('copy') ? res() : rej()
          textArea.remove()
          this.showCode=false
        })
      }
    },
  },
};
</script>

<style lang="scss" >
.copy-code-container {
  width: 100%;

  position: relative;
  .copeBtn {
    position: absolute;
    top: 10px;
    right: 20px;
  }
  .code-box {
    max-height: 800px;
    overflow: auto;
    background-color: #23241f;
    border-radius: 5px;
    font-size: 16px;
  }
  .code-box:hover.copeBtn {
    display: block;
  }
  .copy-container {
    .ant-btn {
    }

    i {
      cursor: pointer;
      font-size: 18px;
      padding: 10px 20px;
    }
  }
}
::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 5px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 10px;
}
::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 5px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #535353;
}
::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background: #ededed;
}
pre{
  margin: 0 !important;
  // margin-top: -20px !important;
}
.hljs{
  // background-color: #eee !important;
}
pre code.hljs{
  padding: 0 20px;
}
 .hljs-comment{
  color: #409EFF !important;
}
</style>